<?php

class OrderController extends Controller {

    public $layout = '//layouts/main';
    public $baseUrl = '';

    public function actionIndex() {

        $this->render('index');
    }

    /**
     * 产品加入购物车
     * 如果是AJAX请求返回状态码, 200代表成功, 400代表失败
     */
    public function actionAddCart() {
        $order = array();

        $order['game_id'] = $_POST['game']; //游戏ID
        $order['server_id'] = $_POST['server']; //服务器ID
        $order['product_type'] = $_POST['product_type']; //产品类型
        $order['num'] = isset($_POST['num']) ? (int) $_POST['num'] : 1; //购买数量
        switch ($order['product_type']) {
            case 'PL'://等级代练
                $order['start_level'] = $_POST['start_level']; //开始等级
                $order['end_level'] = $_POST['end_level']; //结束等级
                break;
            case 'GOLD'://金币产品
            case 'ACCOUNT'://帐号
            case 'PACKAGES'://套餐
            case 'ITEM'://材料
            case 'EQUIPMENT'://装备
            case 'CARD'://点卡
            case 'MEMBER'://会员
            case 'QUEST'://任务
                $order['product_id'] = $_POST['product']; //产品ID
                break;
            case 'SKILL'://技能代练
                $order['skill_id'] = $_POST['skill']; //技能ID
                $order['start_level'] = $_POST['start_level']; //技能开始等级
                $order['end_level'] = $_POST['end_level']; //技能结束等级
                $order['attack'] = $_POST['attack_box']; //攻击
                $order['defence'] = $_POST['defence_box']; //防御
                $order['strength'] = $_POST['strength_box']; //力量
                break;
        }
        //订单属性
        $order_attrs = array();
        if (isset($_POST['Attr'])) {
            foreach ($_POST['Attr'] as $key => $value) {
                $attr = OrderAttribute::model()->findByPk((int) $key);
                $order_attrs[$attr->name] = $value;
            }
        }
        $order['input'] = $order_attrs;

        $cart = new Cart();
        $cart->append($order);
        if (Yii::app()->request->isAjaxRequest) {//如果为AJAX请求返回200
            echo 200;
        } else {
            $this->redirect($this->createUrl('cart'));
        }
    }

    /**
     * 保存客户联系信息
     */
    public function actionAddInformaction() {
        $informaction = $_POST['Customer'];
        if (empty($informaction['f_name']) || empty($informaction['l_name']) || empty($informaction['email']) || empty($informaction['city']) || empty($informaction['address']) || empty($informaction['tel'])) {
            $this->redirect($this->createUrl('cart'));
            Yii::app()->end();
        } else {
            Orders::model()->saveCustomer($informaction);
            if (Yii::app()->request->isAjaxRequest) {
                echo 200;
            } else {
                $this->redirect($this->createUrl('checkOut'));
            }
        }
    }

    /**
     * 删除产品
     * @param string $key
     */
    public function actionRemove($key) {
        $cart = new Cart;
        $cart->remove($key);
        $this->redirect($this->createUrl('cart'));
    }

    /**
     * 修改购物车产品数量，输出总价
     */
    public function actionUpdateNum() {
        if (Yii::app()->request->isAjaxRequest) {
            $key = $_POST['order_key'];
            $num = (int) $_POST['num'];
            $cart = new Cart();
            $cart->updateNum($key, $num);
            $currency_price = WebCurrency::model()->changeCurrency(Orders::model()->totalPrice($cart->orders));
            echo $currency_price['tag'] . $currency_price['price'];
        } else {
            throw new CHttpException(403);
            Yii::app()->end();
        }
    }

    /**
     * 购物车
     */
    public function actionCart() {
        $cart = new Cart();

        //$cart->append(array('product_id' => 1));
        $customer = Orders::model()->getCustomer();

        $this->render('cart', array(
            'cart' => $cart,
            'customer' => $customer,
        ));
    }

    /**
     * 订单确认
     */
    public function actionCheckOut() {
        $basePath = Yii::getPathOfAlias('application.modules.order.theme');
        $baseUrl = Yii::app()->getAssetManager()->publish($basePath);
        $this->baseUrl = $baseUrl;
        $cart = new Cart();
        $customer = Orders::model()->getCustomer();
        $this->render('checkOut', array(
            'cart' => $cart,
            'customer' => $customer,
        ));
    }

    /**
     * 订单支付
     */
    public function actionPayment() {
        session_start();
        $pay_type = $_POST['payment'];
        $cart = new Cart();
        $payment_tag = md5(serialize($cart->orders));
        //$payment_tag!=$_SESSION['order_payment']  && 

        if (!empty($cart->orders)) {
            $_SESSION['order_payment'] = $payment_tag;
            //保存订单基本信息
            $orderModel = new Orders;
            $total_price = $orderModel->totalPrice(); //订单总价
            $currency_price = WebCurrency::model()->changeCurrency($total_price); //计算汇率后总价
            $customer = $orderModel->getCustomer(); //客户信息
            $order_number = $orderModel->generateOrderNumber(); //订单编号
            $_SESSION['order_number'] = $order_number; //使用SESSION保存订单编号, PAYPAL付款时调用
            //计算优惠金额
            $offset = Orders::model()->getOffset($customer['coupon'], $currency_price['price']);
            //$offset_currency = WebCurrency::model()->changeCurrency($offset);

            $orderModel->attributes = array(
                'order_number' => $order_number,
                'total_price' => $currency_price['price'],
                'currency_tag' => $currency_price['code'],
                'comment' => $customer['comment'],
                'coupon' => $customer['coupon'],
                'offset' => $offset,
                'order_date' => time(),
                'uid' => 0,
                'pay_type' => $pay_type,
            );

            if ($orderModel->save()) {
                //保存客户信息
                $ip = Yii::app()->request->getUserHostAddress();
                $customerModel = new OrdersCustomer;
                $customerModel->attributes = array(
                    'order_number' => $order_number,
                    'first_name' => $customer['f_name'],
                    'last_name' => $customer['l_name'],
                    'email' => $customer['email'],
                    'ip' => $ip,
                    'phone' => $customer['tel'],
                    'country' => $customer['country'],
                    'city' => $customer['city'],
                    'address' => $customer['address'],
                    'msn' => $customer['msn'],
                );
                $customerModel->save();

                //保存产品
                $itemModel = new OrdersItems;
                foreach ($cart->orders as $product) {
                    $item = array();
                    $item['order_number'] = $order_number;
                    $item['pid'] = 0;
                    $item['product_type'] = $product['product_type'];
                    $item['num'] = $product['num'];
                    $item['gold_num'] = 0;
                    $item['input'] = serialize($product['input']);
                    $item['game'] = ProductCategory::model()->getGameNameById($product['game_id']);
                    $server = ProductCategory::model()->findByPk($product['server_id']);
                    $item['game_server'] = $server->title;

                    $productInfo = Orders::model()->getProduct($product, $product['num']);
                    $item['name'] = $productInfo['product_name'];
                    $currency_price = WebCurrency::model()->changeCurrency($productInfo['price']); //将价格转为相应的货币
                    $item['price'] = $currency_price['price'];

                    $itemModel->unsetAttributes();
                    $itemModel->setIsNewRecord(TRUE);
                    $itemModel->attributes = $item;
                    $itemModel->save();
                    //print_r($itemModel->errors);
                }

                switch ($pay_type) {
                    case 'paypal':
                    case 'card':
                        $this->redirect($this->createUrl('toPaypal'));
                        break;
                    case 'westernunion':
                        $this->redirect($this->createUrl('toWesternUnion'));
                        break;
                }
            }
        }
    }

    /**
     * 西联支付
     */
    public function actionToWesternUnion() {
        session_start();
        $cart = new Cart();
        $cart->resetCart(); //清空购物车
        //更新支付信息
        if ($cart->cartNum()) {
            $payPal = new Paypal();
            $payPal->reOaApi($_SESSION['order_number']);
        }


        $this->render('western_union');
    }

    /**
     * PAYPAL支付
     */
    public function actionToPaypal() {
        session_start();
        if ($_SESSION['order_number']) {
            $order = Orders::model()->findByAttributes(array('order_number' => $_SESSION['order_number']));
            $customer = OrdersCustomer::model()->findByAttributes(array('order_number' => $_SESSION['order_number']));
            $items = OrdersItems::model()->findAllByAttributes(array('order_number' => $_SESSION['order_number']));
            $paypal = new Paypal;
            $this->render('paypal', array(
                'order' => $order,
                'customer' => $customer,
                'items' => $items,
                'paypal' => $paypal,
            ));
        }
    }

    /**
     * 支付成功返回页面
     */
    public function actionAccess() {
        session_start();
        $cart = new Cart();
        $cart->resetCart(); //清空购物车
        $this->render('access', array(
            'order_number' => $_SESSION['order_number'],
        ));
    }

    /**
     * PAYPAL通信接口
     */
    public function actionIpn() {
        session_start();
        $cart = new Cart();
        $cart->resetCart(); //清空购物车
        //更新支付信息
        $payPal = new Paypal();
        $payPal->ipn();
    }

    /**
     * pay api error
     */
    public function actionApiError() {
        $resArray = $_SESSION['reshash'];
        $this->render('error', array(
            'resArray' => $resArray,
        ));
    }

    /**
     * 检测打折码
     * 返回1说明可用，0不可用
     */
    public function actionCheckCoupon() {
        $coupon = isset($_POST['coupon']) ? $_POST['coupon'] : $_GET['coupon'];
        if (WebCoupon::model()->checkCoupon($coupon)) {
            echo 1;
        } else {
            echo 0;
        }
    }

    /**
     * 获取产品的订单输入项
     */
    public function actionGetAttr() {
        $game_id = (int) $_POST['game'];
        $product_type = $_POST['product_type'];
        $game = ProductCategory::model()->findByPk($game_id);

        $cr = new CDbCriteria;
        $cr->compare('game_id', $game->parentid);
        $cr->compare('product_type', $product_type);
        $cr->compare('status', 1);
        $cr->order = 'order_sort DESC';

        $attrs = array();
        foreach (OrderAttribute::model()->findAll($cr) as $v) {
            $attrs[] = array('name' => $v->name, 'id' => $v->id);
        }
        $product = array('name' => '', 'summary' => '', 'price' => '');
        $server_id = (int) $_POST['server'];
        $game_name = ProductCategory::model()->getGameNameById($game_id);
        $server = ProductCategory::model()->findByPk($server_id);
        switch ($product_type) {
            case 'GOLD':
                $product_id = (int) $_POST['product'];
                $pModel = ProductGold::model()->findByPk($product_id);
                $gold = ProductGold::model()->getGoldPrice($pModel, $server_id);
                if ($gold['save'] > 0) {
                    $summary = $pModel->gold_name . ' <del>' . $gold['tag'] . ($gold['price'] + $gold['save']) . '</del>';
                } else {
                    $summary = $pModel->gold_name;
                }
                $product = array(
                    'name' => $game_name . ' / ' . $server->title . ' / ' . $pModel->gold_name,
                    'summary' => $summary,
                    'price' => $gold['tag'] . $gold['price'],
                );
                break;
            case 'PL':
                $start_level = (int) $_POST['start_level'];
                $end_level = (int) $_POST['end_level'];
                $pl = ProductPowerleveling::model()->getPowerlevelPH($game_id, $start_level, $end_level);
                $price = WebCurrency::model()->changeCurrency($pl->pl_price);
                $time = round($pl->pl_time, 2);
                $product = array(
                    'name' => 'Powerleveling: ' . $start_level . ' - ' . $end_level,
                    'summary' => "<b>Game: </b>$game_name <b>Server: </b>$server->title <b>Hours: </b>$time",
                    'price' => $price['tag'] . $price['price'],
                );
                break;
            case 'SKILL':
                $start_level = (int) $_POST['start_level'];
                $end_level = (int) $_POST['end_level'];
                $skill_id = (int) $_POST['skill'];
                $skill = ProductSkill::model()->findByPk($skill_id);
                $attack = (int) Yii::app()->request->getPost('attack_box');
                $defence = (int) Yii::app()->request->getPost('defence_box');
                $strength = (int) Yii::app()->request->getPost('strength_box');
                $parms = array(
                    'game_id' => $game_id,
                    'skill_id' => $skill_id,
                    'start_level' => $start_level,
                    'end_level' => $end_level,
                    'attack' => $attack,
                    'defence' => $defence,
                    'strength' => $strength,
                );
                $skill_price = ProductSkill::model()->getSkillLevelPH($parms);

                $price = WebCurrency::model()->changeCurrency($skill_price->skill_price);
                $product = array(
                    'name' => $skill->skill_name . ' Powerleveling: ' . $start_level . ' - ' . $end_level,
                    'summary' => "<b>Game: </b>$game_name <b>Server: </b>$server->title <b>Hours: </b>" . $skill_price->skill_time,
                    'price' => $price['tag'] . $price['price'],
                );
                break;
            case 'ITEM':
                $product_id = (int) $_POST['product'];
                $productObj = ProductBase::model()->findByPk($product_id);
                $nums = $productObj->getNums();
                $num = (int) $_POST['num'];
                $discount = 1;
                foreach ($nums['num'] as $key => $v) {
                    if ($v == $num)
                        $discount = $nums['discount'][$key];
                }
                $discount = $discount > 1 ? $discount / 100 : $discount;
                $price = WebCurrency::model()->changeCurrency($num * $productObj->p_price * $discount);
                $product = array(
                    'name' => $productObj->p_name,
                    'summary' => "<b>Game: </b>$game_name",
                    'price' => $price['tag'] . $price['price'],
                );
                break;
            default:
                $product_id = (int) $_POST['product'];
                $productObj = ProductBase::model()->findByPk($product_id);
                $pp = ProductBase::model()->getProductPrice($productObj);

                $product = array(
                    'name' => $productObj->p_name,
                    'summary' => "<b>Game: </b>$game_name",
                    'price' => $pp['tag'] . $pp['price'],
                );
                break;
        }
        echo json_encode(array('attrs' => $attrs, 'product' => $product));
    }

}